<?php

class Stream {
	public $EOF = FALSE;

	function __construct($str = NULL) {
		if ($str !== NULL)
			$this->load($str);
	}
	
	function load($str) {
		$this->source = $str;
		$this->length = strlen($str);
		$this->reset();
	}
	
	function eof() {
		return $this->char === $this->EOF;
	}
	
	function reset() {
		$this->pos = 0;
	}


	function getch() {
		if ($this->pos >= $this->length)
			$c = $this->EOF;
		else {
			$c = $this->source[$this->pos++];			
			$code = ord($c);
			if ($code >= 0xF0 && $code <= 0xF7) {
				$c .= $this->source[$this->pos++];
				$c .= $this->source[$this->pos++];
				$c .= $this->source[$this->pos++];
			} else if ($code >= 0xE0 && $code <= 0xEF) {
				$c .= $this->source[$this->pos++];
				$c .= $this->source[$this->pos++];
			} else if ($code >= 0xC0 && $code <= 0xDF) {
				$c .= $this->source[$this->pos++];
			}
		}
		//echo "*** char: $c\n";
		return $this->char = $c;
	}
	
	function rewind($n) {
		$this->pos -= $n;
	}
}
